package com.squareup.okhttp;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import okio.BufferedSink;
import okio.ByteString;

/**
 * Created by Javen on 14-8-18.
 */
public class FormRequestBody extends RequestBody {
    private static final MediaType CONTENT_TYPE
            = MediaType.parse("application/x-www-form-urlencoded");

    private Map<String, String> params = new HashMap<String, String>();

    public FormRequestBody() {

    }

    public FormRequestBody(Map<String, String> params) {
        if (params != null)
            this.params.putAll(params);
    }

    public void addParams(String key, String value) {
        params.put(key, value);
    }


    @Override
    public MediaType contentType() {
        return CONTENT_TYPE;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        StringBuilder content = new StringBuilder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (content.length() > 0) {
                    content.append('&');
                }
                try {
                    content.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                            .append('=')
                            .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new AssertionError(e);
                }
            }
        }
        sink.write(ByteString.encodeUtf8(content.toString()));
    }
}
